package main

import (
	"fmt"
	"gc-rds-ha/cmd/task/service"
	"gc-rds-ha/internal/common"
	"gc-rds-ha/internal/logger"
	"net/http"
	"os"
	"os/signal"

	"syscall"

	log "github.com/sirupsen/logrus"
)

const GcRdsHaTask = "gc-rds-ha-task"

var (
	quit = make(chan int)
)

// Field name   | Mandatory? | Allowed values  | Allowed special characters
// ----------   | ---------- | --------------  | --------------------------
// Minutes      | Yes        | 0-59            | * / , -
// Hours        | Yes        | 0-23            | * / , -
// Date of month | Yes        | 1-31            | * / , - ?
// Month        | Yes        | 1-12 or JAN-DEC | * / , -
// Date of week  | Yes        | 0-6 or SUN-SAT  | * / , - ?

func main() {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("[main] %s painc:%s.", GcRdsHaTask, r)
			exit(-1)
		}
	}()

	go func() {
		signals := make(chan os.Signal, 1)
		signal.Notify(signals,
			syscall.SIGTERM,
			syscall.SIGINT,
			//syscall.SIGKILL,
			syscall.SIGHUP,
			syscall.SIGQUIT,
		)
		<-signals
		exit(0)
	}()

	go func() { //开启pprof
		log.Printf("[pprof] running.\n")
		log.Println(http.ListenAndServe(fmt.Sprintf("%s:%d", "0.0.0.0", 7081), nil))
	}()

	go service.TaskRun()
	// 初始化日志
	go logger.SetupLogger()
	// 初始化项目配置
	go common.RedirectOutput()

	{ //退出逻辑
		exitCode := <-quit
		log.Printf("[main] %s exit:%d.", GcRdsHaTask, exitCode)
		os.Exit(exitCode)
	}
}

func exit(status int) {
	// ticker.Stop()
	log.Printf("[main] %s stopping.\n", GcRdsHaTask)
	// todo: 关闭数据库连接
	//dao.Close()
	quit <- status
}
